<link rel="stylesheet" href="/assets/home/plugins/mescroll/mescroll.min.css">
<link rel="stylesheet" href="/assets/home/css/coupon_list.css" />

<header class="mui-bar mui-bar-nav mui-bar-nav-bg">
    <a id="icon-menu" class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
    <h1 class="mui-title">我的优惠券</h1>
</header>

<!-- 占位 -->
<div style="height: 50px;"></div>

<div id="coupon" class="mescroll">
    <div class="coupon_list">

    </div>
</div>

<script src="/assets/home/plugins/mescroll/mescroll.min.js"></script>

<script>
    // 实例化插件
    let meScroll = new MeScroll('coupon', {
        // 下拉刷新
        down: {
            auto: false,//是否在初始化完毕之后自动执行下拉回调callback; 默认true
            callback: downCallback // 下拉刷新的回调,别写成downCallback(),多了括号就自动执行方法了
        },
        // 上拉加载
        up: {
            auto: true, //是否在初始化时以上拉加载的方式自动加载第一页数据; 默认false
            isBounce: false, //此处禁止ios回弹,解析(务必认真阅读,特别是最后一点): http://www.mescroll.com/qa.html#q10
            callback: UpCallback, //上拉回调,此处可简写; 相当于 callback: function (page) { upCallback(page); }
            toTop: { //配置回到顶部按钮
                duration: 1000,
                src: "/assets/home/images/mescroll-totop.png", //默认滚动到1000px显示,可配置offset修改
                offset: 100
            }
        }
    });

    async function downCallback() {

        meScroll.resetUpScroll();
        $('#coupon .coupon_list').empty();
        return false;
    }

    async function UpCallback(page) {
        let data = {
            page: page.num,
            limit: page.size,
        }

        let result = await POST({
            url: 'business/coupon_list',
            params: data
        });
        console.log(result);

        if (result.code === 1) {
            let list = result.data.list;

            let receive = result.data.receive;

            let count = result.data.count;

            meScroll.endBySize(list.length - 1, count);

            fetchList(list, receive);
        } else {
            meScroll.endBySize(0, 0);
            mui.toast(result.msg);
            return false;
        }
    }

    function fetchList(list, receive) {
        if (list.length > 0 && receive.length > 0) {
            let Item = '';
            for (let demo of receive) {
                for (let item of list) {
                    if (`${extractData(item, "id")}` === `${extractData(demo, "cid")}`) {
                        Item = `<div class="coupon_item">
                            <div class="item_content">
                                <a href="{:url('/home/coupon/info')}?cid=${extractData(item, "id")}">
                                    <div class="left">
                                        ${extractData(item, "rate") * 100}<span>折</span>
                                    </div>
                                    <div class="right">
                                        <div>${extractData(item, "title")}</div>
                                        <div>活动开始时间：${extractData(item, "createtime_text")}</div>
                                        <div>活动结束时间：${extractData(item, "endtime_text")}</div>
                                        <div>领取时间：${extractData(demo, "createtime_text")}</div>
                                    </div>
                                </a>
                            </div>
                            <div class="item_btn">
                                <button class="btn ${extractData(demo, "status") == 1 ? ' mui-btn-primary' : ''}" data-val="${extractData(item, "id")}">${extractData(demo, "status") == 1 ? '使用' : '已使用'}</button>
                            </div>
                        </div>`;
                        $('#coupon .coupon_list').append(Item);
                        // console.log(`${extractData(demo, "cid")}`);
                        // console.log(`${extractData(item, "id")} === ${extractData(demo, "cid")}`);
                    }
                }
                // console.log(extractData(item,'id'));
            }
        }
    }

    if (window.location.search) {
        $(document).on('click', '.mui-btn-primary', async function (e) {

            let btn = $(event.target);
            //获取优惠卷id
            let couponid = $(event.target).data('val');

            let data = {
                couponid
            }

            let result = await POST({
                url: 'business/buy',
                params: data
            })

            console.log(result);
            if (result.code == 1) {
                mui.toast("使用成功");
                btn.removeClass('mui-btn-primary').text("已使用");
                let sub = result.data;
                setTimeout(function () {
                    window.location.href = "{:url('/home/subject/teacher/confirm')}?subject=" + sub.subid;
                    // console.log("{:url('/home/subject/teacher/confirm')}?subject=" + sub[0].subid);
                }, 2000)
            } else {
                mui.toast("不可使用该优惠卷");
            }

        })

    }

    //从数组里面取出对象的值
    function extractData(obj, key) {
        let result = [];

        if (Array.isArray(obj)) {
            for (let i = 0; i < obj.length; i++) {
                result = result.concat(extractData(obj[i], key));
            }
        } else if (typeof obj === 'object') {
            for (let prop in obj) {
                if (prop === key) {
                    result.push(obj[prop]);
                } else {
                    result = result.concat(extractData(obj[prop], key));
                }
            }
        }

        return result;
    };

</script>